import React, { useState, useEffect, useImperativeHandle, forwardRef, Ref } from 'react';
import { Pagination } from 'antd';
import styles from './index.module.scss';

export interface PageingRefInterface {
  reload: Function
}

export interface PageInterface {
  pageNum: number,
  pageSize: number
}

export interface ResponceInterface {
  total: number,
  list: Array<any>
}

export interface PropsInterface {
  onChange: (pageModel: PageInterface) => void,
  total: number
}

const initData: PageInterface = {
  pageNum: 1,
  pageSize: 10
}

const WPaging = (props: PropsInterface, ref: Ref<any>) => {

  const [page, setPage] = useState<PageInterface>({...initData})

  const clear = function() {
    setPage({...initData})
    props.onChange(initData)
  }

  useEffect(() => {
    props.onChange(initData)
  }, [])

  useImperativeHandle<any, PageingRefInterface>(ref, () => ({
    reload: () => {
      clear()
    },
  }));

  const pageNumChange = function(pageNum: number) {
    page.pageNum = pageNum
    props.onChange(page)
  }

  const pageSizeChange = function(current: number, size: number) {
    page.pageNum = current
    page.pageSize = size
    props.onChange(page)
  }
  
  return <div className={ styles['com-paging'] }>
    <Pagination
      size="small" 
      current={ page.pageNum }
      pageSize={ page.pageSize }
      total={ props.total } 
      onChange={ (page: number) => pageNumChange(page) }
      onShowSizeChange={ (current: number, size: number) => pageSizeChange(current, size) }
      showSizeChanger 
      showQuickJumper 
    />
  </div>
}

export default forwardRef(WPaging)